package org.misalen.web.server.controllers.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.misalen.annotations.ControllerApi;
import org.misalen.annotations.InterfaceApi;
import org.misalen.utils.TextUtil;
import org.misalen.web.database.model.mysql.pro.ProMapAdvertising;
import org.misalen.web.database.model.mysql.pro.ProMapPayInfo;
import org.misalen.web.database.model.mysql.pro.ProMapReward;
import org.misalen.web.database.util.PaginationFrom;
import org.misalen.web.server.config.ErrorCode;
import org.misalen.web.server.config.ServerResult;
import org.misalen.web.server.config.ServerUrl;
import org.misalen.web.server.config.Uncertain;
import org.misalen.web.server.controllers.BaseController;
import org.misalen.web.server.exception.CustomerException;
import org.misalen.web.server.forms.user.MapAdvertisingAddForm;
import org.misalen.web.server.forms.user.MapAdvertisingClickForm;
import org.misalen.web.server.forms.user.MapAdvertisingListForm;
import org.misalen.web.server.forms.user.MapAdvertisingMylistForm;
import org.misalen.web.server.forms.user.MapAdvertisingPrepaidForm;
import org.misalen.web.server.forms.user.MapAdvertisingShareForm;
import org.misalen.web.server.forms.user.MapDetailsForm;
import org.misalen.web.server.forms.user.MyMapDetailsForm;
import org.misalen.web.server.result.Empty;
import org.misalen.web.server.util.FormUtil;
import org.misalen.web.service.pay.alipay.AliPayParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ControllerApi(value = "地图广告", description = "", index = 300)
@RequestMapping(value = ServerUrl.UserMapAdvertisingControllerUrl)
public class UserMapAdvertisingController extends BaseController {

	@RequestMapping(value = "/add", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "发布广告", resultClass = { Empty.class })
	public @ResponseBody ServerResult add(@RequestBody MapAdvertisingAddForm form) throws CustomerException {
		FormUtil.validate(form);
		ProMapAdvertising advertising = new ProMapAdvertising();
		advertising.setAddTime(new Date());
		advertising.setUserId(form.getUserId());
		advertising.setAdverImagesUrl(form.getAdverImagesUrl());
		advertising.setAdverSlogan(form.getAdverSlogan());
		advertising.setPromotionExpenses(form.getPromotionExpenses());
		advertising.setPromotionNumber(form.getPromotionNumber());
		advertising.setPromotionDistance(form.getPromotionDistance());
		advertising.setLongitude(form.getLongitude());
		advertising.setLatitude(form.getLatitude());
		advertising.setGrabThe(TextUtil.booleanToString(false));
		advertising.setCarrierUrl(form.getCarrierUrl());
		advertising.setState("noPay");
		proMapAdvertisingRepository.save(advertising);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("mapId", advertising.getPrimaryKey());
		return ServerResult.ok(map);
	}

	@RequestMapping(value = "/prepaid", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "预支付", resultClass = { Empty.class })
	public @ResponseBody ServerResult prepaid(HttpServletRequest request, @RequestBody MapAdvertisingPrepaidForm form)
			throws Exception {
		FormUtil.validate(form);
		ProMapAdvertising advertising = proMapAdvertisingRepository.get(ProMapAdvertising.class, form.getMapId());
		if (advertising.getState().equals("noPay")) {
			ProMapPayInfo proMapPayInfo = new ProMapPayInfo();
			proMapPayInfo.setMapId(form.getMapId());
			proMapPayInfo.setAddTime(new Date());
			proMapPayInfo.setPayType(form.getPayType());
			proMapPayInfoRepository.save(proMapPayInfo);
			if (form.getPayType().equals("alipay")) {
				AliPayParam myParam = new AliPayParam();
				myParam.setBody(Uncertain.advertisingBody);
				myParam.setSubject(Uncertain.advertisingSubject);
				myParam.setOutTradeNo(proMapPayInfo.getMapId());
				myParam.setTotalAmount(TextUtil.changeF2Y(advertising.getPromotionExpenses().toString()));
				String param = aliPay.getAlipayInfo(myParam, Uncertain.mapAliPayNotifyUrl);
				return ServerResult.ok(param);
			} else {
				String myParam = wechatPay.orderedParam(Uncertain.advertisingBody, proMapPayInfo.getMapId(),
						advertising.getPromotionExpenses().toString(), proMapPayInfo.getMapId(), getIpAddress(request),
						Uncertain.mapWechatNotifyUrl);
				Map<String, Object> map = wechatPay.unifiedorder(myParam);
				return ServerResult.ok(wechatPay.clientParam(map));
			}
		} else {
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_00001);
		}
	}

	@RequestMapping(value = "/list", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "地图广告", resultClass = { PaginationFrom.class, ProMapAdvertising.class }, include = {
			"carrierUrl", "primaryKey", "longitude", "adverSlogan", "latitude", "isGet", "getMoney", "detailsUrl",
			"adverImagesUrl" })
	public PaginationFrom<ProMapAdvertising> list(HttpServletRequest request, @RequestBody MapAdvertisingListForm form)
			throws Exception {
		FormUtil.validate(form);
		PaginationFrom<ProMapAdvertising> pagination = new PaginationFrom<ProMapAdvertising>();
		pagination.setList(
				proMapAdvertisingRepository.findBydistance(form.getLatitude(), form.getLongitude(), form.getUserId()));
		pagination.setRows(pagination.getList().size());
		for (ProMapAdvertising proMapAdvertising : pagination.getList()) {
			proMapAdvertising.setDetailsUrl(getBaseHost(request) + Uncertain.adminUrl
					+ "/pro-map-advertising-preview/details/" + proMapAdvertising.getPrimaryKey());
		}
		return pagination;
	}

	@RequestMapping(value = "/open", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "打开红包", resultClass = { ProMapReward.class })
	public @ResponseBody ServerResult open(@RequestBody MapAdvertisingClickForm form) throws Exception {
		FormUtil.validate(form);
		ProMapAdvertising videoInfo = proMapAdvertisingRepository.getValid(form.getMapId());
		if (videoInfo == null) {
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_10012);
		}
		long validCount = proMapRewardRepository.getValidCountByMap(form.getMapId());
		if (validCount == 0) {
			proMapAdvertisingRepository.updateGrabThe(TextUtil.booleanToString(true), form.getMapId());
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_10012);
		}

		ProMapReward proWebReward = proMapRewardRepository.getByVideoUser(form.getUserId(), form.getMapId());
		if (proWebReward != null) {
			return ServerResult.error(ErrorCode.SYS_ERROR_CODE_10013);
		}
		proWebReward = proMapRewardRepository.getValidByVideo(form.getMapId());
		proUserRepository.updateBalance(proWebReward.getMoney(), form.getUserId());
		proUserRepository.updateFreezeBalance(proWebReward.getMoney2(), form.getUserId());
		proWebReward.setGetTime(new Date());
		proWebReward.setUserId(form.getUserId());
		proMapRewardRepository.update(proWebReward);
		if (validCount == 1) {
			proMapAdvertisingRepository.updateGrabThe(TextUtil.booleanToString(true), form.getMapId());
		}
		return ServerResult.ok(proWebReward);
	}

	@RequestMapping(value = "/details", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "详情", resultClass = { PaginationFrom.class, ProMapReward.class }, include = { "userId",
			"getTime", "money", "userName" })
	public PaginationFrom<ProMapReward> details(@RequestBody MapDetailsForm form) throws CustomerException {
		FormUtil.validate(form);
		return proMapRewardRepository.getListByGet(form.getMapId());
	}
	
	@RequestMapping(value = "/mydetails", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "详情", resultClass = { PaginationFrom.class, ProMapReward.class })
	public PaginationFrom<ProMapReward> mydetails(@RequestBody MyMapDetailsForm form) throws CustomerException {
		FormUtil.validate(form);
		PaginationFrom<ProMapReward> pagination = formToPage(form, ProMapReward.class);
		return proMapRewardRepository.getMyDetailList(form.getMapId(), pagination);
	}
	
	@RequestMapping(value = "/mylist", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "我的地图广告", resultClass = { PaginationFrom.class, ProMapAdvertising.class })
	public PaginationFrom<ProMapAdvertising> mylist(HttpServletRequest request,
			@RequestBody MapAdvertisingMylistForm form) throws CustomerException {
		FormUtil.validate(form);
		PaginationFrom<ProMapAdvertising> pagination = formToPage(form, ProMapAdvertising.class);
		pagination = proMapAdvertisingRepository.findByUser(form.getUserId(), form.getState(), pagination);
		for (ProMapAdvertising webAdvertising : pagination.getList()) {
			webAdvertising.setDetailsUrl(getBaseHost(request) + Uncertain.adminUrl
					+ "/pro-map-advertising-preview/details/" + webAdvertising.getPrimaryKey());
		}
		return pagination;
	}

	@RequestMapping(value = "/share", method = { RequestMethod.POST }, produces = "application/json")
	@InterfaceApi(value = "分享参数(返回url)", resultClass = {})
	public @ResponseBody ServerResult share(HttpServletRequest request, @RequestBody MapAdvertisingShareForm form)
			throws CustomerException {
		FormUtil.validate(form);
		ProMapAdvertising mapAdvertising = proMapAdvertisingRepository.get(ProMapAdvertising.class, form.getMapId());
		Map<String, String> map = new HashMap<String, String>();
		ProMapReward proMapReward = proMapRewardRepository.getByVideoUser(form.getUserId(), form.getMapId());
		if (proMapReward == null || proMapReward.getGetTime2() != null) {
			map.put("url", getBaseHost(request) + Uncertain.adminUrl + "/pro-map-advertising-preview/details/"
					+ mapAdvertising.getPrimaryKey());
		} else {
			map.put("url", getBaseHost(request) + Uncertain.adminUrl + "/pro-map-advertising-preview/share/"
					+ proMapReward.getPrimaryKey());
		}
		return ServerResult.ok(map);
	}
}
